//
//  RegistViewController.m
//  coba-iOS
//
//  Created by 郭四虎 on 15/11/16.
//  Copyright © 2015年 YouKu. All rights reserved.
//

#import "RegistViewController.h"
#import "MyMD5.h"
#import "MyTabBarController.h"

@interface RegistViewController ()<UITextFieldDelegate>
{
    bool _canSubmit;
    UIWebView *_web;
}
@property (weak, nonatomic) IBOutlet UITextField *numTf;
@property (weak, nonatomic) IBOutlet UITextField *verificationcodeTf;
@property (weak, nonatomic) IBOutlet UITextField *passwordTf;
@property (weak, nonatomic) IBOutlet UIButton *isAgree;
@property (weak, nonatomic) IBOutlet UIButton *verificationcodeBtn;
@property (assign, nonatomic) NSInteger timeNmum;
@property (strong, nonatomic) NSTimer *getTime;

@end

@implementation RegistViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _canSubmit = NO;
    self.title = @"注册";
    
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"8"] style:UIBarButtonItemStylePlain target:self action:@selector(forwardBack)];
    
    self.navigationItem.leftBarButtonItem = leftItem;
    
    
}

- (void)forwardBack
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (IBAction)getVerificationcode:(UIButton *)sender {
    
    if((![self valiMobile:_numTf.text])|(_numTf.text.length == 0)){
        [self.view Message:@"请输入正确手机号" HiddenAfterDelay:1];
        return;
    }
    _verificationcodeBtn.enabled = NO;
    _timeNmum = 60;
    NSDateFormatter *formater = [[NSDateFormatter alloc]init];
    [formater setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *str = [formater stringFromDate:[NSDate date]];
    
    NSDictionary *parameters = @{@"login_id":_numTf.text,@"phone":_numTf.text,@"update_time":str};
    
    [MyAFN POST:GETVERFICATIONCODE parameters:parameters block:^(id responseObject) {
        NSDictionary *dic = responseObject;
        _verificationcodeBtn.enabled = YES;
        
        if ([[dic objectForKey:@"status"]integerValue]) {
            _getTime = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(begainTime) userInfo:nil repeats:YES];
        }else{
            [self.view Message:[dic objectForKey:@"msg"] HiddenAfterDelay:1];
        }
    }error:^(NSError *error) {
        
        _verificationcodeBtn.enabled = YES;
    }fromController:nil];
    
}
- (void)begainTime
{
    if (_timeNmum > 0) {
        _timeNmum--;
        [_verificationcodeBtn setTitle:[NSString stringWithFormat:@"%ldS",(long)_timeNmum] forState:UIControlStateNormal];
        _verificationcodeBtn.enabled = NO;
    }else{
        _timeNmum = 0;
        if ([_getTime isValid]) {
            [_getTime invalidate];
            _getTime = nil;
        }
        [_verificationcodeBtn setTitle:@"重新获取" forState:UIControlStateNormal];
        _verificationcodeBtn.enabled = YES;
    }
    
}

- (IBAction)submitClick:(UIButton *)sender {
    if (_isAgree.selected) {
        [self.view Message:@"未同意" HiddenAfterDelay:1];
        return;
    }
    
    if((![self valiMobile:_numTf.text])|(_numTf.text.length == 0)){
        [self.view Message:@"请输入正确手机号" HiddenAfterDelay:1];
        return;
    }
    if (!_verificationcodeTf.text.length) {
        [self.view Message:@"请获取并输入验证码" HiddenAfterDelay:1];
        return;
    }
    if ((_passwordTf.text.length < 6)|(_passwordTf.text.length > 23)) {
        [self.view Message:@"请设置正确的密码" HiddenAfterDelay:1];
        return;
    }
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSDictionary *parameters = @{@"login_id":_numTf.text};
    
    
    [MyAFN POST:REGISTCHECK parameters:parameters block:^(id responseObject) {
        
        NSDictionary *registcheckDic = responseObject;
        
        if (![[registcheckDic objectForKey:@"status"]integerValue]) {
            [self performSelector:@selector(exist) withObject:nil afterDelay:0.5];
            return;
        }
        
        NSDateFormatter *formater = [[NSDateFormatter alloc]init];
        [formater setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSString *date = [formater stringFromDate:[NSDate date]];
        
        NSDictionary *para = @{@"login_id":_numTf.text,@"password":[MyMD5 md5:_passwordTf.text],@"login_type":@1,@"name":_numTf.text,@"create_date":date,@"image_code":_verificationcodeTf.text,@"name":_numTf.text};
        if (_canSubmit) {
            

        [MyAFN POST:REGIST parameters:para block:^(id responseObject) {
            
            NSDictionary *registDic = responseObject;
            
            if ([[registDic objectForKey:@"status"]integerValue]) {
                
                [[NSUserDefaults standardUserDefaults]setObject:_numTf.text forKey:@"userid"];
                [[NSUserDefaults standardUserDefaults]setObject:[MyMD5 md5:_passwordTf.text] forKey:@"userpwd"];
                [[NSUserDefaults standardUserDefaults]setObject:_numTf.text forKey:@"username"];
                
                [self toLogin];
                
            }else{
                [self performSelector:@selector(showErr) withObject:nil afterDelay:0.5];
            }
        }error:^(NSError *error) {
            
        }fromController:self];
        }else{
            [self performSelector:@selector(showErr) withObject:nil afterDelay:0.5];

        }
    }error:^(NSError *error) {
        
    }fromController:self];

    
}
- (void)exist
{
    [self.view Message:@"该账号已存在" HiddenAfterDelay:0.5];
}

- (void)showMsg
{
    [self.view Message:@"注册成功，即将进入应用" HiddenAfterDelay:1];
}

- (void)showErr
{
    [self.view Message:@"注册失败,请确认信息填写正确" HiddenAfterDelay:1];
}

- (void)getIn
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)toLogin
{
    if (USERID) {
        NSDictionary *parameters = @{@"login_id":USERID,@"password":USERPWD,@"login_ip":[Myuser getIPAddress],@"login_date":[MyDateformater getCurrentDate]};
        [MyAFN POST:LOGIN parameters:parameters block:^(id responseObject) {
            
            NSDictionary *dic = responseObject;
            
            if (dic) {
                if ([[dic objectForKey:@"status"]integerValue]) {
                    
                    [MobClick profileSignInWithPUID:_numTf.text];
                    
                    [[Myuser sharedUser]setValuesForKeysWithDictionary:dic];
                    
                    [[NSUserDefaults standardUserDefaults]setObject:USERID forKey:@"userid"];
                    
                    [[NSUserDefaults standardUserDefaults]setObject:USERPWD forKey:@"userpwd"];
                    
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeUserinfo" object:nil];
                    
                    [self performSelector:@selector(showMsg) withObject:nil afterDelay:0.5];
                    
                    [self performSelector:@selector(getIn) withObject:nil afterDelay:1.5];
                    
                }else{
                    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"userid"];
                    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"usericon"];
                    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"username"];
                    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"userpwd"];
                    
                    [self performSelector:@selector(showErr) withObject:dic afterDelay:0.5];
                }
                
            }
        }error:^(NSError *error) {
            
        }fromController:self];
    }
}

- (IBAction)userProtocal:(UIButton *)sender {
    NSString *str = @"<h3 style=\"text-align: center\">APP免责声明</h3><p>1、一切移动客户端用户在下载并浏览APP软件时均被视为已经仔细阅读本条款并完全同意。凡以任何方式登陆本APP，或直接、间接使用本APP资料者，均被视为自愿接受本网站相关声明和用户服务协议的约束。</p><p>2、APP转载的内容并不代表APP之意见及观点，也不意味着本网赞同其观点或证实其内容的真实性。</p><p>3、APP转载的文字、图片、音视频等资料均由本APP用户提供，其真实性、准确性和合法性由信息发布人负责。APP不提供任何保证，并不承担任何法律责任。 </p><p>4、APP所转载的文字、图片、音视频等资料，如果侵犯了第三方的知识产权或其他权利，责任由作者或转载者本人承担，本APP对此不承担责任。  </p><p>5、APP不保证为向用户提供便利而设置的外部链接的准确性和完整性，同时，对于该外部链接指向的不由APP实际控制的任何网页上的内容，APP不承担任何责任。</p><p>6、用户明确并同意其使用APP网络服务所存在的风险将完全由其本人承担；因其使用APP网络服务而产生的一切后果也由其本人承担，APP对此不承担任何责任。 </p><p>7、除APP注明之服务条款外，其它因不当使用本APP而导致的任何意外、疏忽、合约毁坏、诽谤、版权或其他知识产权侵犯及其所造成的任何损失，APP概不负责，亦不承担任何法律责任。</p><p> 8、对于因不可抗力或因黑客攻击、通讯线路中断等APP不能控制的原因造成的网络服务中断或其他缺陷，导致用户不能正常使用APP，APP不承担任何责任，但将尽力减少因此给用户造成的损失或影响。</p><p>9、本声明未涉及的问题请参见国家有关法律法规，当本声明与国家有关法律法规冲突时，以国家法律法规为准。</p>";
    if (!_web) {
        _web = [[UIWebView alloc]initWithFrame:CGRectMake(30, 100, WIDTH-60, HEIGHT-200)];
        _web.scrollView.bounces = NO;
        _web.alpha = 0;
    }
    [self.view addSubview:_web];
    [UIView animateWithDuration:0.3 animations:^{
        _web.alpha = 1;
    }];
    
    [_web loadHTMLString:str baseURL:nil];
}
- (IBAction)isAgree:(UIButton *)sender {
    sender.selected = !sender.selected;

}

- (BOOL)valiMobile:(NSString *)mobilePhone {
    //验证手机号
    //移动号段正则表达式
    NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
    //联通号段正则表达式
    NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
    //电信号段正则表达式
    NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
    NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
    BOOL isMatch1 = [pred1 evaluateWithObject:mobilePhone];
    NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
    BOOL isMatch2 = [pred2 evaluateWithObject:mobilePhone];
    NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
    BOOL isMatch3 = [pred3 evaluateWithObject:mobilePhone];
    
    if (isMatch1 || isMatch2 || isMatch3){
        return YES;
    }
    return NO;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{

    if (textField.text.length != 4) {
        [self.view Message:@"请输入4位验证码" HiddenAfterDelay:1];
    }else{
        if(!_numTf.text.length){
            
            [self.view Message:@"请输入手机号" HiddenAfterDelay:1];
            return;
        }
            NSDictionary *parameters = @{@"phone":_numTf.text,@"send_code":_verificationcodeTf.text};
            [MyAFN POST:CHECKVERFICATIONCODE parameters:parameters block:^(id responseObject) {
               
                NSDictionary *dic = responseObject;
                
                if (![[dic objectForKey:@"status"]integerValue]) {
                    
                    [self performSelector:@selector(showE) withObject:nil afterDelay:0.5];
                    _canSubmit = NO;
                }else{
                    
                    _canSubmit = YES;
                }
            }error:^(NSError *error) {
                
            }fromController:self];
    
    }
}

- (void)showE
{
    [self.view Message:@"验证码有误" HiddenAfterDelay:1];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    if (touch.view != _web) {
        [UIView animateWithDuration:0.3 animations:^{
            
            _web.alpha = 0;
        } completion:^(BOOL finished) {
            
            [_web removeFromSuperview];
        }];
        
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
